package org.adream.account.service.ws;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.apache.cxf.helpers.DOMUtils;

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
	
	private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	private String clientId;
	
	private String clientToken;
	
	private String timestamp;
	
	private String clientSecret;
	
	public AuthInterceptor(String clientId, String clientToken, String timestamp,
			String clientSecret) {
		super(Phase.PREPARE_SEND);
		this.clientId = clientId;
		this.clientToken = clientToken;
		this.timestamp = timestamp;
		this.clientSecret = clientSecret;
	}

	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		logger.debug("come to client auth");
		Document document = DOMUtils.createDocument();
		//根节点
		Element rootEle = document.createElementNS("", "AuthenticationRequest");
		Element clientIdEle = document.createElement("client_id");
		clientIdEle.setTextContent(clientId);
		rootEle.appendChild(clientIdEle);
		Element clientTokenEle = document.createElement("client_token");
		clientTokenEle.setTextContent(clientToken);
		rootEle.appendChild(clientTokenEle);
		Element timestampEle = document.createElement("timestamp");
		timestampEle.setTextContent(timestamp);
		rootEle.appendChild(timestampEle);
		Element clientSecretEle = document.createElement("client_secret");
		clientSecretEle.setTextContent(clientSecret);
		rootEle.appendChild(clientSecretEle);
		//头信息
        List<Header> headers = message.getHeaders();
        QName qname = new QName("auth");
        SoapHeader head = new SoapHeader(qname, rootEle);
        headers.add(head);
	}
}